﻿using Common;
using Dm;
using FCT551.Base;
using FCT551.Helper;
using FCT551.Models;
using FCT551.Views;
using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace FCT551.ViewModels
{
    public class CollectDataViewModel : NotifyPorperChanged
    {
        public static updateHandler updatemessage;
        private CollectDateView _collectDateView;
        public static CancellationTokenSource _TokenSource;
        private List<DataEntryModel> _datasList;

        public CollectDataViewModel(CollectDateView collectDateView)
        {
            PWMChannels = new ObservableCollection<int>()
            {
                1,2,3,4,5,6,7,8,11,12,13,14,21,22,23,24,101,102,103,104
            };
            _datasList = new();
            _collectDateView = collectDateView;
            Cards = new();
            Card1 = new();
            Card2 = new();
            Card3 = new();
            init();
            WindowLoadedCommand = new Command() { ExeAction = new Action<object>(WindowLoadedcmd) };
            WindowClosingCommand = new Command() { ExeAction = new Action<object>(WindowClosingcmd) };
            StartCollectCommand = new Command() { ExeAction = new Action<object>(StartCollectCmd) };
            StopCollectCommand = new Command() { ExeAction = new Action<object>(StopCollectCmd) };
            SaveToCsvCollectCommand = new Command() { ExeAction = new Action<object>(SaveToCsvCollectCmd) };
            ChangePowerOutStatus = new Command() { ExeAction = new Action<object>(ChangePowerOutStatuscmd) };
            PowerSetCurrentCommand = new Command() { ExeAction = new Action<object>(PowerSetCurrentCmd) };
            PowerSetVoltageCommand = new Command() { ExeAction = new Action<object>(PowerSetVoltageCmd) };
            PowerGetCurrentCommand = new Command() { ExeAction = new Action<object>(PowerGetCurrentCmd) };
            PowerGetVoltageCommand = new Command() { ExeAction = new Action<object>(PowerGetVoltageCmd) };
            SetPwmValueCommand = new Command() { ExeAction = new Action<object>(SetPwmValueCmd) };
            SetAllPwmValueCommand = new Command() { ExeAction = new Action<object>(SetAllPwmValueCmd) };
            SetOnePwmValueCommand = new Command() { ExeAction = new Action<object>(SetOnePwmValueCmd) };
            ReadPwmValueCommand = new Command() { ExeAction = new Action<object>(ReadPwmValueCmd) };
        }

        #region 初始化命令和参数

        private string _readPwmValue;

        public string ReadPwmValue
        {
            set
            {
                _readPwmValue = value; this.SetProperty();
            }
            get
            {
                return _readPwmValue;
            }
        }

        private string _setPwmValue;

        public string SetPwmValue
        {
            set
            {
                _setPwmValue = value; this.SetProperty();
            }
            get
            {
                return _setPwmValue;
            }
        }

        private string _setALLPwmValue;

        public string SetALLPwmValue
        {
            set
            {
                _setALLPwmValue = value; this.SetProperty();
            }
            get
            {
                return _setALLPwmValue;
            }
        }

        private string _setonePwmValue;

        public string SetOnePwmValue
        {
            set
            {
                _setonePwmValue = value; this.SetProperty();
            }
            get
            {
                return _setonePwmValue;
            }
        }

        private string _powerSetCurrent;

        public string PowerSetCurrent
        {
            set
            {
                _powerSetCurrent = value; this.SetProperty();
            }
            get
            {
                return _powerSetCurrent;
            }
        }

        private string _powerstatus;

        public string PowerStatus
        {
            set
            {
                _powerstatus = value; this.SetProperty();
            }
            get
            {
                return _powerstatus;
            }
        }

        private string _powerSetVoltage;

        public string PowerSetVoltage
        {
            set
            {
                _powerSetVoltage = value; this.SetProperty();
            }
            get
            {
                return _powerSetVoltage;
            }
        }

        private string _powerGetCurrent;

        public string PowerGetCurrent
        {
            set
            {
                _powerGetCurrent = value;
                this.SetProperty();
            }
            get
            {
                return _powerGetCurrent;
            }
        }

        private string _powerGetVoltage;

        public string PowerGetVoltage
        {
            set
            {
                _powerGetVoltage = value; this.SetProperty();
            }
            get
            {
                return _powerGetVoltage;
            }
        }

        private int _powerSetChannel;

        public int PowerSetChannel
        {
            set
            {
                _powerSetChannel = value; this.SetProperty();
            }
            get
            {
                return _powerSetChannel;
            }
        }

        private int _setpwmchannel;

        public int SetPWMChannel
        {
            set
            {
                _setpwmchannel = value; this.SetProperty();
            }
            get
            {
                return _setpwmchannel;
            }
        }

        private int _powerGetChannel;

        public int PowerGetChannel
        {
            set
            {
                _powerGetChannel = value; this.SetProperty();
            }
            get
            {
                return _powerGetChannel;
            }
        }

        private ObservableCollection<int> pWMChannels;

        public ObservableCollection<int> PWMChannels
        {
            get => pWMChannels;
            set
            {
                pWMChannels = value;
                this.SetProperty();
            }
        }

        private Command _powerSetCurrentCommand;

        /// <summary>
        /// 设置电流方法
        /// </summary>
        public Command PowerSetCurrentCommand
        {
            set
            {
                _powerSetCurrentCommand = value;
            }
            get
            {
                return _powerSetCurrentCommand;
            }
        }

        private Command _powerSetVoltageCommand;

        /// <summary>
        /// 设置电压方法
        /// </summary>
        public Command PowerSetVoltageCommand
        {
            set
            {
                _powerSetVoltageCommand = value;
            }
            get
            {
                return _powerSetVoltageCommand;
            }
        }

        private Command _readPwmValueCommand;

        /// <summary>
        /// 读取默认频率
        /// </summary>
        public Command ReadPwmValueCommand
        {
            set
            {
                _readPwmValueCommand = value;
            }
            get
            {
                return _readPwmValueCommand;
            }
        }

        private Command _setPwmValueCommand;

        /// <summary>
        /// 设置默认频率
        /// </summary>
        public Command SetPwmValueCommand
        {
            set
            {
                _setPwmValueCommand = value;
            }
            get
            {
                return _setPwmValueCommand;
            }
        }

        private Command _setAllPwmValueCommand;

        /// <summary>
        /// 设置所有通道占空比
        /// </summary>
        public Command SetAllPwmValueCommand
        {
            set
            {
                _setAllPwmValueCommand = value;
            }
            get
            {
                return _setAllPwmValueCommand;
            }
        }

        private Command _setOnePwmValueCommand;

        /// <summary>
        /// 设置单通道占空比
        /// </summary>
        public Command SetOnePwmValueCommand
        {
            set
            {
                _setOnePwmValueCommand = value;
            }
            get
            {
                return _setOnePwmValueCommand;
            }
        }

        private Command _powerGetCurrentCommand;

        /// <summary>
        /// 读取电流方法
        /// </summary>
        public Command PowerGetCurrentCommand
        {
            set
            {
                _powerGetCurrentCommand = value;
            }
            get
            {
                return _powerGetCurrentCommand;
            }
        }

        private Command _powerGetVoltageCommand;

        /// <summary>
        /// 读取电压方法
        /// </summary>
        public Command PowerGetVoltageCommand
        {
            set
            {
                _powerGetVoltageCommand = value;
            }
            get
            {
                return _powerGetVoltageCommand;
            }
        }

        private Command _startcollectCommand;

        /// <summary>
        /// 开始采集
        /// </summary>
        public Command StartCollectCommand
        {
            set
            {
                _startcollectCommand = value;
            }
            get
            {
                return _startcollectCommand;
            }
        }

        private Command _stopcollectCommand;

        /// <summary>
        /// 停止采集
        /// </summary>
        public Command StopCollectCommand
        {
            set
            {
                _stopcollectCommand = value;
            }
            get
            {
                return _stopcollectCommand;
            }
        }

        private Command _savetocsvcollectCommand;

        /// <summary>
        /// 保存到csv文件
        /// </summary>
        public Command SaveToCsvCollectCommand
        {
            set
            {
                _savetocsvcollectCommand = value;
            }
            get
            {
                return _savetocsvcollectCommand;
            }
        }

        private Command _changePowerOutStatus;

        /// <summary>
        /// 改变电源输出状态
        /// </summary>
        public Command ChangePowerOutStatus
        {
            set
            {
                _changePowerOutStatus = value;
            }
            get
            {
                return _changePowerOutStatus;
            }
        }

        private Command _windowLoadedCommand;

        public Command WindowLoadedCommand
        {
            set
            {
                _windowLoadedCommand = value;
            }
            get
            {
                return _windowLoadedCommand;
            }
        }

        private Command _windowClosingCommand;

        public Command WindowClosingCommand
        {
            set
            {
                _windowClosingCommand = value;
            }
            get
            {
                return _windowClosingCommand;
            }
        }

        private ObservableCollection<ObservableCollection<CollectDataModel>> _cards;

        /// <summary>
        /// 所有的电压采集卡
        /// </summary>
        public ObservableCollection<ObservableCollection<CollectDataModel>> Cards
        {
            set
            {
                _cards = value;
                this.SetProperty();
            }
            get
            {
                return _cards;
            }
        }

        private ObservableCollection<CollectDataModel> _card1;

        /// <summary>
        /// 电压采集卡1
        /// </summary>
        public ObservableCollection<CollectDataModel> Card1
        {
            set
            {
                _card1 = value;
                this.SetProperty();
            }
            get
            {
                return _card1;
            }
        }

        private ObservableCollection<CollectDataModel> _card2;

        /// <summary>
        /// 电压采集卡2
        /// </summary>
        public ObservableCollection<CollectDataModel> Card2
        {
            set
            {
                _card2 = value;
                this.SetProperty();
            }
            get
            {
                return _card2;
            }
        }

        private ObservableCollection<CollectDataModel> _card3;

        /// <summary>
        /// 电压采集卡3
        /// </summary>
        public ObservableCollection<CollectDataModel> Card3
        {
            set
            {
                _card3 = value;
                this.SetProperty();
            }
            get
            {
                return _card3;
            }
        }

        #endregion 初始化命令和参数

        #region 绑定方法

        /// <summary>
        /// 设置单工位占空比
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void SetOnePwmValueCmd(object obj)
        {
            if (int.TryParse(SetOnePwmValue, out int res))
            {
                int channl = SetPWMChannel;
                if (res < 0 || res > 100)
                {
                    return;
                }
                int really = 100 - res;
                if (channl < 100)
                {
                    Global._qjxPwm16.SetOneStation(channl, really);
                }
                else
                {
                    channl -= 100;
                    Global._qjxPwm4.SetOneStation(channl, really);
                }
            }
        }

        /// <summary>
        /// 读取默认频率
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ReadPwmValueCmd(object obj)
        {
            ReadPwmValue = Global._qjxPwm16.GetDeFaultFreunency().ToString() + "," + Global._qjxPwm4.GetDeFaultFreunency().ToString();
        }

        /// <summary>
        /// 设置所有通道占空比
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void SetAllPwmValueCmd(object obj)
        {
            if (int.TryParse(SetALLPwmValue, out int res))
            {
                if (res < 0 || res > 100)
                {
                    return;
                }
                int really = 100 - res;
                Global._qjxPwm16.SetALLStation(really);
                Global._qjxPwm4.SetALLStation(really);
            }
        }

        /// <summary>
        /// 设置默认频率
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void SetPwmValueCmd(object obj)
        {
            if (int.TryParse(SetPwmValue, out int res))
            {
                Global._qjxPwm16.SetDeFaultFreunency(res);
                Global._qjxPwm4.SetDeFaultFreunency(res);
            }
        }

        /// <summary>
        /// 获取电压
        /// </summary>
        /// <param name="obj"></param>
        private void PowerGetVoltageCmd(object obj)
        {
            PowerGetVoltage = Global._RU_12_3040.GetVoltage().ToString();
        }

        /// <summary>
        /// 获取电流
        /// </summary>
        /// <param name="obj"></param>
        private void PowerGetCurrentCmd(object obj)
        {
            PowerGetCurrent = Global._RU_12_3040.GetCurrent().ToString();
        }

        /// <summary>
        /// 设置电压
        /// </summary>
        /// <param name="obj"></param>
        private void PowerSetVoltageCmd(object obj)
        {
            if (PowerSetVoltage == null || PowerSetVoltage == "")
            {
                return;
            }
            if (double.TryParse(PowerSetVoltage, out double value))
            {
                Global._RU_12_3040.SetVoltage(value);
            }
        }

        /// <summary>
        /// 设置电流
        /// </summary>
        /// <param name="obj"></param>
        private void PowerSetCurrentCmd(object obj)
        {
            if (PowerSetCurrent == null || PowerSetCurrent == "")
            {
                return;
            }
            if (double.TryParse(PowerSetCurrent, out double value))
            {
                Global._RU_12_3040.SetCurrent(value);
            }
        }

        private string csvpath = AppDomain.CurrentDomain.BaseDirectory;
        /// <summary>

        /// 结果保存至CSV文件
        /// </summary>
        /// <param name="obj"></param>
        private void SaveToCsvCollectCmd(object obj)
        {
            string pahh = Path.Combine(csvpath, "DateCsvOut.csv");
            if (!File.Exists(pahh))
            {
                File.Create(pahh).Close(); // 立即关闭流
                Console.WriteLine("CSV文件已创建");
            }

            Dates = Global._ZH44242G14F2_Voltage.RegisterValues;
            using (var writer = new StreamWriter(pahh))
            {
                // 写入表头（Key作为列名）
                writer.WriteLine(string.Join(",", Dates.Keys));

                // 获取最大行数
                int maxRows = Dates.Values.Max(list => list?.Count ?? 0);

                // 逐行写入数据
                for (int row = 0; row < maxRows; row++)
                {
                    var line = new List<string>();
                    foreach (var key in Dates.Keys)
                    {
                        var value = Dates[key]?.Count > row ? Dates[key][row].ToString() : "";
                        line.Add(value);
                    }
                    writer.WriteLine(string.Join(",", line));
                }
            }

            UpdateMessage("写入CSV文件成功");
        }

        /// <summary>
        /// 改变电源输出状态
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ChangePowerOutStatuscmd(object obj)
        {
            if (PowerStatus == null || PowerStatus == "")
            {
                return;
            }
            if (PowerStatus == "1")
            {
                Global._RU_12_3040.SetStatus(true);
            }
            else if (PowerStatus == "0")
            {
                Global._RU_12_3040.SetStatus(false);
            }
        }

        /// <summary>
        /// 关闭采集
        /// </summary>
        /// <param name="obj"></param>
        private void StopCollectCmd(object obj)
        {
            _TokenSource.Cancel();
            Application.Current.Dispatcher.Invoke(() =>
            {
                init();
            });
        }

        private Dictionary<int, List<double>> Dates = new();

        /// <summary>
        /// 开始采集
        /// </summary>
        /// <param name="obj"></param>
        private async void StartCollectCmd(object obj)
        {
            try
            {
                Dates = new();
                Global._ZH44242G14F2_Voltage.ClearRegisterValues();
                Global._ZH44242G14F2_Current.ClearRegisterValues();
                _datasList = new List<DataEntryModel>();
                int index = Convert.ToInt32(obj) - 1;
                _TokenSource.Cancel();
                await Task.Delay(1000);
                _TokenSource = new();

                if (index == 0)
                {
                    //执行读取电压
                    _ = Task.Run(async () =>
                    {
                        while (!_TokenSource.IsCancellationRequested)
                        {
                            for (int i = 0; i < 20; i++)
                            {
                                var value = Global._ZH44242G14F2_Voltage.GetRegisterReallyValue(i);
                                Cards[index][i].Index = value;
                            }

                            await Task.Delay(100);
                        }
                    }, _TokenSource.Token);
                }
                else
                {
                    //执行读取电流
                    _ = Task.Run(async () =>
                    {
                        while (!_TokenSource.IsCancellationRequested)
                        {
                            for (int i = 0; i < 20; i++)
                            {
                                var value = Global._ZH44242G14F2_Current.GetRegisterReallyValue(i);
                                Cards[index][i].Index = value;
                            }
                            await Task.Delay(100);
                        }
                    }, _TokenSource.Token);
                }
            }
            catch (Exception e)
            {
                MyLog.Error(e);
            }
        }

        /// <summary>
        /// 界面退出方法
        /// </summary>
        private void WindowClosingcmd(object obj)
        {
            _TokenSource.Cancel();
        }

        /// <summary>
        /// 界面加载方法
        /// </summary>
        /// <param name="obj"></param>
        private void WindowLoadedcmd(object obj)
        {
            _TokenSource = new CancellationTokenSource();
            Application.Current.Dispatcher.Invoke(() =>
            {
                init();
            });
        }

        private void init()
        {
            Cards = new();
            Card1 = [];
            Card2 = [];
            Card3 = [];

            for (int i = 0; i < 20; i++)
            {
                Card1.Add(new CollectDataModel() { IndexName = "通道：" + (i + 1).ToString(), Index = 0 });
                Card2.Add(new CollectDataModel() { IndexName = "通道：" + (i + 1).ToString(), Index = 0 });
                Card3.Add(new CollectDataModel() { IndexName = "通道：" + (i + 1).ToString(), Index = 0 });
            }

            Cards.Add(Card1);
            Cards.Add(Card2);
            Cards.Add(Card3);
        }

        private void UpdateMessage(string msg, Models.LogLevel logLevel = Models.LogLevel.Info)
        {
            Application.Current.Dispatcher.BeginInvoke(() =>
            {
                updatemessage?.Invoke(msg, logLevel);
            });
        }

        #endregion 绑定方法
    }
}